package com.wangyf.thread.c_021_question;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * @author wangyf
 * @date 2021/1/21 21:00
 * Semaphore控制同一时间只能有一个线程运行
 * 让 t2 在 t1里面执行  ，防止t1执行完成 t2还未启动
 */
public class T06_Semaphore {
    public static void main(String[] args) {
        Semaphore s = new Semaphore(1);

        List<Object> list = new ArrayList<>();

        Thread t2 = new Thread(() -> {
            try {
                s.acquire();
                System.out.println("t2 start");
                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread t1 = new Thread(() -> {
            System.out.println("t1 start");
            try {
                s.acquire();
                for (int i = 0; i < 10; i++) {
                    System.out.println(i);
                    list.add(new Object());
                    if (list.size() == 5) {
                        s.release();
                        t2.start();
                        t2.join();
                        s.acquire();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });

        t1.start();
    }
}
